package com.czxy.servlet;

import cn.itcast.servlet.BaseServlet;
import cn.itcast.vcode.VerifyCode;
import com.czxy.domain.User;
import com.czxy.service.UserService;

import javax.servlet.annotation.WebServlet;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {


    public String login() {
        User user = toBean(User.class);

        UserService service = new UserService();

        User loginU = service.login(user);

        if (loginU == null) {

            getRequest().setAttribute("loginInfo", "登录名失败或密码错误");
            getRequest().setAttribute("user", user);

            return "/jsp/login.jsp";

        } else {

            getSession().setAttribute("loginU", loginU);
            return "redirect:/jsp/index.jsp";

        }


    }




    //校验验证码逻辑
   public  void checkVcCode() throws IOException {

        //获取前端传递的  vcText
       String vcText = getRequest().getParameter("vcText");
       //获取session中的  vcCode
       String vcCode = getRequest().getParameter("vcCode");
       //移除session中的  vcCode
       getSession().removeAttribute("vcCode");

       //比较是否相同并给出响应
      if (vcText == null || vcCode == null || "".equals(vcCode) || "".equals(vcText)){
          //校验失败

//          {"message":"校验失败","flag":false}

          getResponse().getWriter().write("{\"message\":\"校验失败\",\"flag\":false}");
          return;
      }

      if (vcText.equalsIgnoreCase(vcCode)){
          getResponse().getWriter().write("{\"message\":\"校验成功\",\"flag\":true}");

      }else{

          getResponse().getWriter().write("{\"message\":\"校验失败\",\"flag\":false}");
      }















   }















    public  void  getVcImg() throws IOException {

        //生成验证码图片
        VerifyCode verifyCode = new VerifyCode();
        BufferedImage image = verifyCode.getImage();

        //把码值存储session
        String vcCode = verifyCode.getText();
        getSession().setAttribute("vcCode",vcCode);
        //给前端响应

        VerifyCode.output(image,getResponse().getOutputStream());










    }













    UserService service = new UserService();


    public String register(){

        User user = toBean(User.class);

        UserService service = new UserService();

        service.register(user);

        return "redirect:/jsp/login.jsp";



    }





    public  void  checkUsername() throws IOException {

        //接收 username
        String username = getRequest().getParameter("username");


        UserService service = new UserService();

        List<User> list = service.findUserByUsername(username);

        if (list.size() == 0){
            //用户名可用
//            {"message":"用户名可用","flag":true}

            getResponse().getWriter().write("{\"message\":\"用户名可用\",\"flag\":true}");
        }else{

            getResponse().getWriter().write("{\"message\":\"用户名不可用\",\"flag\":false}");
        }


    }
}
